$(document).ready(function () {

    function createDots() {
        for (var i = 1; i <= 7; i++) {
            var div = $('<div class="divDots">').addClass('dot').css('transition', 'right ' + (0.6 + i / 10).toFixed(1) + 's ease-out');
            div.css('top', '0');
            div.prependTo($('#widget_preview'));


        }
    }
  
    function loadDots() {
        var i = 0;
        animateDots();
        function animateDots() {
            setTimeout(function () {
                var dots = $('div.dot');

                if (dots.length) {
                    dots.toggleClass('open');
                }
                i++;
                if (i < 1) {
                    animateDots();
                } else {
                }
            }, 1300)
        }
    }

    $('#nav-logout').click(function (e) {
        e.preventDefault();

        createDots();
        loadDots();

        setTimeout(function () {
            $.ajax({
                url: "scripts/Clear.aspx",
                global: false,
                type: "GET",
                async: false,
                success: function () {
                    $("#myprofilePage").addClass("flipped");
                    var current = window.location.href;
                    var pos = current.lastIndexOf('/');
                    var redirect = current.substring(0, pos) + "/index.aspx";

                    window.location.href = redirect;
                }
            });
        }, 2500);
    });


    /// Update Profile
    setUserProfile();

    /// On Tab click
    $('.nav-subtab-ctrl').click(function () {
        setUserProfile();
    });

    $('#btnUpdateProfile').click(function () {

        var profile = jQuery.parseJSON(getUserProfile());


        var args = new Object();


        args.Country = $('#countryUpdate').val();
        args.EmailAddress = $('#emailAddressUpdate').val();
        args.FirstName = $('#firstnameUpdate').val();
        args.LastName = $('#lastnameUpdate').val();
        args.Id = getUserID();
        //args.Sex =  $('#genderUpdate').val();
        args.Organization = $('#organizationUpdate').val();
        args.Purpose = $('#purposeUpdate').val();
        args.Title = $('#titleUpdate').val();
       // args.Username = $('#usernameUpdate').val();
        //args.Password = password;
        console.log(args);

        var updateUserProfile = $.ajax({
            type: 'POST',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/user/update/" + getUserID(),
            data: JSON.stringify(args),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var objResponse = jQuery.parseJSON(updateUserProfile);
        console.log("here111:" + objResponse);
     
       
        if (objResponse.ErrorDetail == "Updation Failed.Operation is not valid due to the current state of the object.") {
            $('#updateInfo').html('An unexpected error occurred while trying to update user profile. You may try later.');
           
        } else {
            $('#updateInfo').fadeIn(1000);
            $('#updateInfo').html('User Profile has been successfully updated. The new details are available under My Profile tab.');
        }

    });

    $('#btnDeleteUser').click(function () {

        /// Get user password
        var password = $('#passwordConfirm').val();

        if (password == "Password Confirmation") {
            $("#passwordConfirm").css("outline", "3px solid rgb(235, 46, 46)");
            $("#passwordConfirm").css("margin-left", "20px");
            $("#passwordConfirm").css("margin-top", "3px");
            $("#passwordConfirm").css("width", "88%");
            return false;
        }

        var args = new Object();
        var profile = jQuery.parseJSON(getUserProfile());

        args.Username = profile.response.Username;
        args.Password = password;
        args.Id = getUserID();

        var deleteUserProfile = $.ajax({
            type: 'POST',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/user/delete/" + getUserID(),
            data: JSON.stringify(args),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        console.log(deleteUserProfile);

        if (deleteUserProfile) {
            $('#profileSection').fadeOut("slow");
            $('#containerCenter').fadeOut("slow");

            $('#deleteMessage').html('Thank you for using our services. Your profile has been successfully removed from our Database System. You will be redirected to the index page.');
            $('#deleteMessage').fadeIn(1000);
            createDots();
            loadDots();

            setTimeout(function () {
                $.ajax({
                    url: "scripts/Clear.aspx",
                    global: false,
                    type: "GET",
                    async: false,
                    success: function () {
                        $("#myprofilePage").addClass("flipped");
                        var current = window.location.href;
                        var pos = current.lastIndexOf('/');
                        var redirect = current.substring(0, pos) + "/index.aspx";

                        window.location.href = redirect;
                    }
                });
            }, 7000);
        }

    });

    function setUserProfile() {

        var profile = jQuery.parseJSON(getUserProfile());
        console.log("here");
        console.log(profile);
        $('#titleUpdate').val(profile.response.Title);
        $('#firstnameUpdate').val(profile.response.FirstName);
        $('#lastnameUpdate').val(profile.response.LastName);
        //$('#usernameUpdate').val(profile.response.Username);
        // $('#genderUpdate').val(profile.response.Sex);
        $('#emailAddressUpdate').val(profile.response.EmailAddress);
        $('#countryUpdate').val(profile.response.Country);
        $('#organizationUpdate').val(profile.response.Organization);
        $('#purposeUpdate').val(profile.response.Purpose);


        $('#userid').text(profile.response.Id);
        $('#title').text(profile.response.Title);
        $('#firstname').text(profile.response.FirstName);
        $('#lastname').text(profile.response.LastName);
        $('#username').text(profile.response.Username);
        // $('#genderUpdate').text(profile.response.Sex);
        $('#emailaddress').text(profile.response.EmailAddress);
        $('#country').text(profile.response.Country);
        $('#organization').text(profile.response.Organization);
        $('#purpose').text(profile.response.Purpose);

    }



    function getUserProfile() {
        var userProfile = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/user/" + getUserID(),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        return userProfile;
    }

    function getUserID() {
        var userID = $.ajax({
            type: 'GET',
            url: "scripts/GetSessions.aspx",
            data: { "UserId": "true" },
            dataType: 'html',
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        return userID;
    }
});